import React from 'react';
import { Modal, Form, Input, Select } from 'antd';
import { BaseForm } from '../Form/BaseForm';
import type { Material, CreateMaterialRequest, UpdateMaterialRequest } from '../../../api/types/material';

const { Option } = Select;
const { TextArea } = Input;

interface MaterialModalProps {
  visible: boolean;
  editingMaterial: Material | null;
  onSubmit: (values: CreateMaterialRequest | UpdateMaterialRequest) => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
}

export const MaterialModal: React.FC<MaterialModalProps> = ({
  visible,
  editingMaterial,
  onSubmit,
  onCancel,
  loading = false,
}) => {
  const [form] = Form.useForm();

  React.useEffect(() => {
    if (visible) {
      if (editingMaterial) {
        form.setFieldsValue({
          name: editingMaterial.name,
          category: editingMaterial.category,
          location: editingMaterial.location,
          status: editingMaterial.status,
          description: editingMaterial.description,
          borrowerName: editingMaterial.borrowerName
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          status: 'available',
          category: '未分类',
          location: '未指定'
        });
      }
    }
  }, [visible, editingMaterial, form]);

  const handleSubmit = async (values: CreateMaterialRequest | UpdateMaterialRequest) => {
    // try {
    //   await onSubmit(values);
    //   form.resetFields();
    // } catch (error) {
    //   throw error;
    // }
    try {
    
      const cleanData = { ...values };
      delete (cleanData as any).quantity;
      delete (cleanData as any).available;
      await onSubmit(cleanData);
      form.resetFields();
    } catch (error) {
      throw error;
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={editingMaterial ? '编辑物资' : '新增物资'}
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={600}
      destroyOnClose
    >
      <BaseForm
        form={form}
        onFinish={handleSubmit}
        onCancel={handleCancel}
        submitText={editingMaterial ? '更新' : '创建'}
        cancelText="取消"
        layout="vertical"
        loading={loading}
      >
        <Form.Item
          label="物资名称"
          name="name"
          rules={[
            { required: true, message: '请输入物资名称' },
            { min: 2, max: 50, message: '物资名称长度为2-50个字符' }
          ]}
        >
          <Input placeholder="请输入物资名称" />
        </Form.Item>

        <Form.Item
          label="分类"
          name="category"
          rules={[
            { required: true, message: '请输入分类' },
            { min: 2, max: 20, message: '分类长度为2-20个字符' }
          ]}
        >
          <Input placeholder="请输入分类" />
        </Form.Item>

        <Form.Item
          label="存放位置"
          name="location"
          rules={[
            { required: true, message: '请输入存放位置' },
            { min: 2, max: 50, message: '存放位置长度为2-50个字符' }
          ]}
        >
          <Input placeholder="请输入存放位置" />
        </Form.Item>

        <Form.Item
          label="状态"
          name="status"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Option value="available">可用</Option>
            <Option value="maintenance">维护中</Option>
            <Option value="scrapped">已报废</Option>
            <Option value="borrowed">借用中</Option>
          </Select>
        </Form.Item>

        <Form.Item shouldUpdate>
          {() => {
            const status = form.getFieldValue('status');
            return status === 'borrowed' ? (
              <Form.Item
                label="借用者"
                name="borrowerName"
                rules={[
                  { required: true, message: '请输入借用者姓名' },
                  { min: 2, max: 10, message: '借用者姓名长度为2-10个字符' }
                ]}
              >
                <Input placeholder="请输入借用者姓名" />
              </Form.Item>
            ) : null;
          }}
        </Form.Item>

        <Form.Item
          label="描述"
          name="description"
          rules={[
            { max: 500, message: '描述不能超过500个字符' }
          ]}
        >
          <TextArea
            placeholder="请输入物资描述（可选）"
            rows={3}
            showCount
            maxLength={500}
          />
        </Form.Item>
      </BaseForm>
    </Modal>
  );
};